package com.ewanghuiju.app.ui.main.activity;

import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.azhon.appupdate.config.UpdateConfiguration;
import com.azhon.appupdate.manager.DownloadManager;
import com.ewanghuiju.app.R;
import com.ewanghuiju.app.app.App;
import com.ewanghuiju.app.app.Constants;
import com.ewanghuiju.app.app.ForegroundCallbacks;
import com.ewanghuiju.app.base.BaseActivity;
import com.ewanghuiju.app.base.contract.my.MainContract;
import com.ewanghuiju.app.jpush.TagAliasOperatorHelper;
import com.ewanghuiju.app.model.bean.response.UserInfoResponBean;
import com.ewanghuiju.app.model.bean.response.VersionResponBean;
import com.ewanghuiju.app.model.dp.RealmHelper;
import com.ewanghuiju.app.model.prefs.ImplPreferencesHelper;
import com.ewanghuiju.app.presenter.home.MainPresenter;
import com.ewanghuiju.app.ui.home.activity.SearchShopResultActivity;
import com.ewanghuiju.app.ui.home.fragment.HomeFragment;
import com.ewanghuiju.app.ui.my.fragment.MyFragment;
import com.ewanghuiju.app.ui.pintuan.activity.PintuanClassifyFragment;
import com.ewanghuiju.app.ui.pintuan.activity.PintuanShopDetailsActivity;
import com.ewanghuiju.app.ui.shopmail.fragment.ShopmailFragment;
import com.ewanghuiju.app.util.ClipboardUtils;
import com.ewanghuiju.app.util.StartActivityUtil;
import com.ewanghuiju.app.widget.popupwindow.CommonSearchPopup;
import com.ewanghuiju.app.widget.popupwindow.PopupItemClickCallback;

import java.util.List;

import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;
import butterknife.BindView;
import butterknife.OnClick;
import me.yokeyword.fragmentation.SupportFragment;

import static com.ewanghuiju.app.jpush.TagAliasOperatorHelper.ACTION_DELETE;
import static com.ewanghuiju.app.jpush.TagAliasOperatorHelper.ACTION_SET;
import static com.ewanghuiju.app.jpush.TagAliasOperatorHelper.sequence;

public class MainActivity extends BaseActivity<MainPresenter> implements MainContract.View, ViewPager.OnPageChangeListener, ForegroundCallbacks.Listener {

    @BindView(R.id.iv_main_tab_home)
    ImageView iv_main_tab_home;
    @BindView(R.id.iv_main_tab_mail)
    ImageView iv_main_tab_mail;
    @BindView(R.id.iv_main_tab_my)
    ImageView iv_main_tab_my;
    @BindView(R.id.tv_main_tab_home)
    TextView tv_main_tab_home;
    @BindView(R.id.tv_main_tab_mail)
    TextView tv_main_tab_mail;
    @BindView(R.id.tv_main_tab_my)
    TextView tv_main_tab_my;

    HomeFragment homeFragment = null;
    PintuanClassifyFragment pintuanClassifyFragment = null;
    ShopmailFragment shopmailFragment = null;
    MyFragment myFragment = null;
    @BindView(R.id.iv_main_tab_vip)
    ImageView ivMainTabVip;
    @BindView(R.id.tv_main_tab_vip)
    TextView tvMainTabVip;
//    @BindView(R.id.bottomBar)
//    BottomBar mBottomBar;

    //    private List<Fragment> mFragments;
    private List<String> titleList;

    private CommonSearchPopup commonSearchPopup;

    public static final int FIRST = 0;
    public static final int SECOND = 1;
    public static final int THIRD = 2;
    public static final int FOURTH = 3;


    private SupportFragment[] mFragments = new SupportFragment[4];

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initEventAndData() {
        int welcomTOMainType = getIntent().getIntExtra(Constants.TO_MAIN_TYPE, 1);
        if (welcomTOMainType == 2) {
            String goodsId = getIntent().getStringExtra(Constants.TO_MAIN_VALUE);
            if (!TextUtils.isEmpty(goodsId)) {
                try {
                    new StartActivityUtil(mContext, PintuanShopDetailsActivity.class).putExtra(Constants.PINTUAN_SHOP_ID,
                            Integer.valueOf(goodsId))
                            .startActivity(true);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        } else if (welcomTOMainType == 3) {
            String group_no = getIntent().getStringExtra(Constants.TO_MAIN_VALUE);
            //拼团详情
            if (!TextUtils.isEmpty(group_no)) {
                new StartActivityUtil(mContext, SearchShopResultActivity.class).putExtra(Constants.SEARCH_BODY,
                        group_no)
                        .startActivity(true);
            }
        }
//        Uri uri = getIntent().getData();
//        if (uri != null) {
//            String mType = uri.getQueryParameter("mw_cp_type");
//            if (!TextUtils.isEmpty(mType)) {
//                if (mType.equals("1")) {
//                    //商品详情
//                    String goodsId = uri.getQueryParameter("goods_id");
//                    if (!TextUtils.isEmpty(goodsId)) {
//                        try {
//                            new StartActivityUtil(mContext, PintuanShopDetailsActivity.class).putExtra(Constants.PINTUAN_SHOP_ID,
//                                    Integer.valueOf(goodsId))
//                                    .startActivity(true);
//                        } catch (NumberFormatException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                } else if (mType.equals("2")) {
//                    //拼团详情
//                    String group_no = uri.getQueryParameter("mw_cp_group_no");
//                    if (!TextUtils.isEmpty(group_no)) {
//                        new StartActivityUtil(mContext, SearchShopResultActivity.class).putExtra(Constants.SEARCH_BODY,
//                                group_no)
//                                .startActivity(true);
//                    }
//                }
//            }
//        }
        // 注册监听
        ForegroundCallbacks.get(App.getInstance()).addListener(this);
        getUpgradeInfo();

//        register (this);
        //jpush  setAlias
//        setJpushAlias();
        int mainType = getIntent().getIntExtra(Constants.TO_MAIN, 1);
        SupportFragment firstFragment = findFragment(HomeFragment.class);
        if (firstFragment == null) {
            mFragments[FIRST] = HomeFragment.newInstance();
            mFragments[SECOND] = PintuanClassifyFragment.newInstance();
            mFragments[THIRD] = ShopmailFragment.newInstance();
            mFragments[FOURTH] = MyFragment.newInstance();

            loadMultipleRootFragment(R.id.fl_container, FIRST,
                    mFragments[FIRST],
                    mFragments[SECOND],
                    mFragments[THIRD],
                    mFragments[FOURTH]);
        } else {
            // 这里库已经做了Fragment恢复,所有不需要额外的处理了, 不会出现重叠问题

            // 这里我们需要拿到mFragments的引用
            mFragments[FIRST] = firstFragment;
            mFragments[SECOND] = findFragment(PintuanClassifyFragment.class);
            mFragments[THIRD] = findFragment(ShopmailFragment.class);
            mFragments[FOURTH] = findFragment(MyFragment.class);
        }
        /**
         * 跳转到会员权益
         */
        if (mainType == 3) {
            jumpToVip();
        }else{
//            if (prePosition == 0) {
//                return;
//            }
            showHideFragment(mFragments[0], mFragments[prePosition]);
            reset();
            tv_main_tab_home.setTextColor(getResources().getColor(R.color.tab_color_select));
            iv_main_tab_home.setImageResource(R.mipmap.tab_home_select);
            prePosition = 0;
        }
    }

    /**
     * 获取版本更新信息
     */
    public void getUpgradeInfo() {
        //版本更新
        try {
            PackageManager pm = mContext.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
            mPresenter.getUpgradeInfo(pi.versionName, Constants.PHONE_TYPE);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳转到会员权益
     */
    public void jumpToVip() {
        try {
            if (prePosition == 2) {
                return;
            }
            showHideFragment(mFragments[2], mFragments[prePosition]);
            reset();
            tvMainTabVip.setTextColor(getResources().getColor(R.color.tab_color_select));
            ivMainTabVip.setImageResource(R.mipmap.tab_vip_select);
            prePosition = 2;
//            shopmailFragment.toCurrentVip();
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置极光Alias
     */
    private void setJpushAlias() {
        ImplPreferencesHelper mImplPreferencesHelper = App.getAppComponent().preferencesHelper();
        if (mImplPreferencesHelper.getIsAlias()) {
            return;
        }
        RealmHelper realmHelper = App.getAppComponent().realmHelper();
        UserInfoResponBean userInfoResponBean = realmHelper.getUserInfoResponBean();
        if (userInfoResponBean != null && !TextUtils.isEmpty(userInfoResponBean.getMobile())) {
            TagAliasOperatorHelper.TagAliasBean tagAliasBean = new TagAliasOperatorHelper.TagAliasBean();
            tagAliasBean.setAction(ACTION_SET);
            sequence++;
            tagAliasBean.setAlias(userInfoResponBean.getMobile());
            tagAliasBean.setAliasAction(true);
            TagAliasOperatorHelper.getInstance().handleAction(getApplicationContext(), sequence, tagAliasBean);
        } else {
            TagAliasOperatorHelper.TagAliasBean tagAliasBean = new TagAliasOperatorHelper.TagAliasBean();
            tagAliasBean.setAction(ACTION_DELETE);
            sequence++;
            tagAliasBean.setAliasAction(true);
            TagAliasOperatorHelper.getInstance().handleAction(getApplicationContext(), sequence, tagAliasBean);
        }
//        JPushInterface.getAlias(activity, sequence);
    }

    private int prePosition = 0;

    @OnClick({R.id.ll_main_tab_home, R.id.ll_main_tab_mail, R.id.ll_main_tab_vip, R.id.ll_main_tab_my})
    public void onViewClicked(View view) {
        //切换到不同的fragment，并且显示点击动画
        int id = view.getId();
        switch (id) {
            case R.id.ll_main_tab_home:
                if (prePosition == 0) {
                    return;
                }
                showHideFragment(mFragments[0], mFragments[prePosition]);
                reset();
//                viewPager.setCurrentItem(0);
                tv_main_tab_home.setTextColor(getResources().getColor(R.color.tab_color_select));
                iv_main_tab_home.setImageResource(R.mipmap.tab_home_select);
                prePosition = 0;
                break;
            case R.id.ll_main_tab_mail:
                if (prePosition == 1) {
                    return;
                }
                showHideFragment(mFragments[1], mFragments[prePosition]);
                reset();
//                viewPager.setCurrentItem(1);
                tv_main_tab_mail.setTextColor(getResources().getColor(R.color.tab_color_select));
                iv_main_tab_mail.setImageResource(R.mipmap.tab_center_select);
                prePosition = 1;
                break;
            case R.id.ll_main_tab_vip:
                if (prePosition == 2) {
                    return;
                }
                showHideFragment(mFragments[2], mFragments[prePosition]);
                reset();
//                viewPager.setCurrentItem(2);
                tvMainTabVip.setTextColor(getResources().getColor(R.color.tab_color_select));
                ivMainTabVip.setImageResource(R.mipmap.tab_vip_select);
                prePosition = 2;
                break;
            case R.id.ll_main_tab_my:
                if (prePosition == 3) {
                    return;
                }
                showHideFragment(mFragments[3], mFragments[prePosition]);
                reset();
//                viewPager.setCurrentItem(3);
                tv_main_tab_my.setTextColor(getResources().getColor(R.color.tab_color_select));
                iv_main_tab_my.setImageResource(R.mipmap.tab_my_select);
                prePosition = 3;
                break;
            default:
                break;
        }
    }


    //    public void resetStatusBarColor(@ColorInt int statusBarColor) {
//    /*Sofia.with(activity)
//            .statusBarDarkFont()
//            .statusBarBackground(statusBarColor);*/
//
//        StatusBar.setStatusBarLightMode(this, statusBarColor);
//
//    }
    private void reset() {
        tv_main_tab_home.setTextColor(ContextCompat.getColor(mContext, R.color.tab_color_normal));
        iv_main_tab_home.setImageResource(R.mipmap.tab_home_normal);
        tv_main_tab_mail.setTextColor(ContextCompat.getColor(mContext, R.color.tab_color_normal));
        iv_main_tab_mail.setImageResource(R.mipmap.tab_center_normal);
        tvMainTabVip.setTextColor(ContextCompat.getColor(mContext, R.color.tab_color_normal));
        ivMainTabVip.setImageResource(R.mipmap.tab_vip_normal);
        tv_main_tab_my.setTextColor(ContextCompat.getColor(mContext, R.color.tab_color_normal));
        iv_main_tab_my.setImageResource(R.mipmap.tab_my_normal);
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private long TOUCH_TIME = 0;  //点击返回键时间

    @Override
    public void onBackPressedSupport() {
        if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
            pop();
        } else {
            if ((System.currentTimeMillis() - TOUCH_TIME) > 2000) {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                TOUCH_TIME = System.currentTimeMillis();
            } else {
                App.getInstance().exitApp();
            }
        }
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void showUpgradeInfo(VersionResponBean versionResponBean) {
        startUpdate(versionResponBean);
    }

    private void startUpdate(VersionResponBean versionResponBean) {
        if (versionResponBean == null || versionResponBean.getIs_update() == 0) {
            return;
        }
        /*
         * 整个库允许配置的内容
         */
        UpdateConfiguration configuration = new UpdateConfiguration()
                //输出错误日志
                .setEnableLog(false)
                //设置自定义的下载
                //.setHttpManager()
                //下载完成自动跳动安装页面
                .setJumpInstallPage(true)
                //设置对话框背景图片 (图片规范参照demo中的示例图)
                .setDialogImage(R.mipmap.icon_upgrad_dialog_bg)
                //设置按钮的颜色
                .setDialogButtonColor(Color.parseColor("#DA291C"))
                //设置对话框强制更新时进度条和文字的颜色
                .setDialogProgressBarColor(Color.parseColor("#DA291C"))
                //设置按钮的文字颜色
                .setDialogButtonTextColor(Color.WHITE)
                //设置是否显示通知栏进度
                .setShowNotification(true)
                //设置是否提示后台下载toast
                .setShowBgdToast(true)
                //设置强制更新
                .setForcedUpgrade(versionResponBean.getIs_more() == 1);
        //设置对话框按钮的点击监听
//                .setButtonClickListener(this)
        //设置下载过程的监听
//                .setOnDownloadListener(this);

        DownloadManager manager = DownloadManager.getInstance(this);
        manager.setApkName(TextUtils.isEmpty(versionResponBean.getApkName()) ? (System.currentTimeMillis() + ".apk") : versionResponBean.getApkName())
                .setApkUrl(versionResponBean.getDownload_url())
                .setSmallIcon(R.mipmap.icon_logo)
                .setShowNewerToast(true)
                .setConfiguration(configuration)
                .setApkVersionCode(versionResponBean.getVersionCode())
                .setApkVersionName(versionResponBean.getVersion())
                .setApkSize(versionResponBean.getApkSize())
                .setApkDescription(versionResponBean.getContent())
                .download();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 移除监听
        ForegroundCallbacks.get(App.getInstance()).removeListener(this);
    }

//    @Override
//    protected void onResume() {
//        super.onResume();
//        Intent mIntent = getIntent();
//        Uri uri = mIntent.getData();
//        if (uri != null) {
//            String mType = uri.getQueryParameter("type");
//            if (!TextUtils.isEmpty(mType)) {
//                if (mType.equals("1")) {
//                    //商品详情
//                    String goodsId = uri.getQueryParameter("goods_id");
//                    if (!TextUtils.isEmpty(goodsId)) {
//                        new StartActivityUtil(mContext, PintuanShopDetailsActivity.class).putExtra(Constants.PINTUAN_SHOP_ID,
//                                goodsId)
//                                .startActivity(true);
//                    }
//                } else if (mType.equals("2")) {
//                    //拼团详情
//                    String group_no = uri.getQueryParameter("group_no");
//                    if (!TextUtils.isEmpty(group_no)) {
//                        new StartActivityUtil(mContext, SearchShopResultActivity.class).putExtra(Constants.SEARCH_BODY,
//                                group_no)
//                                .startActivity(true);
//                    }
//                }
//            }
//        }
//    }

    @Override
    public void onBecameForeground() {
        // 切换为前台
        if (prePosition >= 2) {
            return;
        }
        Activity mActivity = App.getInstance().getCurrentActivity();
        if (mActivity == null || !(mActivity instanceof MainActivity)) {
            return;
        }
        //判断粘贴板是否存在内容
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                CharSequence mCharSequence = ClipboardUtils.getText();
                String clipboardText = TextUtils.isEmpty(mCharSequence) ? "" : mCharSequence.toString();
                if (clipboardText.length() > 0) {
                    ClipboardUtils.copyText("", "");
                    if (commonSearchPopup != null) {
                        commonSearchPopup.setContent(clipboardText);
                        commonSearchPopup.showPopupWindow();
                        return;
                    }
                    commonSearchPopup = new CommonSearchPopup(mContext,
                            new PopupItemClickCallback() {

                                @Override
                                public void onSureCallback(String text) {

                                    new StartActivityUtil(mContext, SearchShopResultActivity.class).putExtra(Constants.SEARCH_BODY,
                                            text)
                                            .startActivity(true);
                                }

                                @Override
                                public void onTextChangedCallback(String text) {

                                }
                            });
                    commonSearchPopup.setPopupGravity(Gravity.CENTER);
                    commonSearchPopup.setWidth(commonSearchPopup.getScreenWidth() * 2 / 3);
                    commonSearchPopup.setContent(clipboardText);
                    commonSearchPopup.showPopupWindow();
                }
            }
        }, 500);
    }

    @Override
    public void onBecameBackground() {
        //到后台
    }

//    private void register(Context context){
////        JMLinkAPI.getInstance().registerDefault(new JMLinkCallback() {
////            @Override
////            public void execute(Map<String, String> paramMap, Uri uri) {
////                JMLinkIntentBuilder.buildIntent(paramMap, context, DefaultRouteActivity.class);
////            }
////        });
//        JMLinkAPI.getInstance().register("ewhjlink_shopinfo", new JMLinkCallback() {
//            public void execute(Map<String, String> paramMap, Uri uri) {
//                JMLinkIntentBuilder.buildIntent(paramMap, context, SearchShopResultActivity.class);
//            }
//        });
//    }

//    private static void unregister() {
////        JMLinkAPI.getInstance().unregisterDefault();
//        JMLinkAPI.getInstance().unregister("ewhjlink_shopinfo");
//    }
}
